// 视频平台主要JavaScript功能

class VideoPlatform {
    constructor() {
        this.init();
    }

    init() {
        this.setupNavbar();
        this.setupUpload();
        this.setupSearch();
        this.setupVideoCards();
        this.setupAnimations();
    }

    // 导航栏滚动效果
    setupNavbar() {
        const navbar = document.querySelector('.navbar');
        if (!navbar) return;

        window.addEventListener('scroll', () => {
            if (window.scrollY > 50) {
                navbar.classList.add('scrolled');
            } else {
                navbar.classList.remove('scrolled');
            }
        });
    }

    // 文件上传功能
    setupUpload() {
        const uploadArea = document.querySelector('.upload-area');
        const fileInput = document.getElementById('videoFile');
        
        if (!uploadArea || !fileInput) return;

        // 拖拽上传
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });

        uploadArea.addEventListener('dragleave', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                this.handleFileUpload(files[0]);
            }
        });

        // 点击上传
        uploadArea.addEventListener('click', () => {
            fileInput.click();
        });

        fileInput.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                this.handleFileUpload(e.target.files[0]);
            }
        });
    }

    // 处理文件上传
    async handleFileUpload(file) {
        if (!this.validateFile(file)) return;

        const formData = new FormData();
        formData.append('file', file);
        formData.append('title', document.getElementById('videoTitle')?.value || file.name);
        formData.append('description', document.getElementById('videoDescription')?.value || '');

        try {
            this.showUploadProgress(0);
            
            const response = await fetch('/api/upload/video', {
                method: 'POST',
                body: formData
            });

            const result = await response.json();

            if (result.success) {
                this.showMessage('视频上传成功！', 'success');
                this.showUploadProgress(100);
                
                // 3秒后跳转到视频页面
                setTimeout(() => {
                    window.location.href = `/video/${result.video.id}`;
                }, 3000);
            } else {
                this.showMessage(result.message || '上传失败', 'error');
                this.hideUploadProgress();
            }
        } catch (error) {
            this.showMessage('上传失败: ' + error.message, 'error');
            this.hideUploadProgress();
        }
    }

    // 验证文件
    validateFile(file) {
        const allowedTypes = ['video/mp4', 'video/avi', 'video/mov', 'video/wmv', 'video/flv', 'video/webm', 'video/mkv'];
        const maxSize = 500 * 1024 * 1024; // 500MB

        if (!allowedTypes.includes(file.type)) {
            this.showMessage('不支持的文件格式，请上传视频文件', 'error');
            return false;
        }

        if (file.size > maxSize) {
            this.showMessage('文件大小不能超过500MB', 'error');
            return false;
        }

        return true;
    }

    // 显示上传进度
    showUploadProgress(percent) {
        let progressContainer = document.querySelector('.upload-progress');
        
        if (!progressContainer) {
            progressContainer = document.createElement('div');
            progressContainer.className = 'upload-progress';
            progressContainer.innerHTML = `
                <div class="progress-bar">
                    <div class="progress-fill" style="width: 0%"></div>
                </div>
                <div class="progress-text">上传中... 0%</div>
            `;
            document.querySelector('.upload-area').appendChild(progressContainer);
        }

        const progressFill = progressContainer.querySelector('.progress-fill');
        const progressText = progressContainer.querySelector('.progress-text');
        
        progressFill.style.width = percent + '%';
        progressText.textContent = `上传中... ${percent}%`;

        if (percent === 100) {
            progressText.textContent = '上传完成！';
            setTimeout(() => {
                this.hideUploadProgress();
            }, 2000);
        }
    }

    // 隐藏上传进度
    hideUploadProgress() {
        const progressContainer = document.querySelector('.upload-progress');
        if (progressContainer) {
            progressContainer.remove();
        }
    }

    // 搜索功能
    setupSearch() {
        const searchInput = document.getElementById('searchInput');
        const searchButton = document.querySelector('.search-button');
        
        if (!searchInput) return;

        // 搜索按钮点击
        if (searchButton) {
            searchButton.addEventListener('click', () => {
                this.performSearch(searchInput.value);
            });
        }

        // 回车搜索
        searchInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.performSearch(searchInput.value);
            }
        });

        // 实时搜索建议
        let searchTimeout;
        searchInput.addEventListener('input', (e) => {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                if (e.target.value.length > 2) {
                    this.showSearchSuggestions(e.target.value);
                } else {
                    this.hideSearchSuggestions();
                }
            }, 300);
        });
    }

    // 执行搜索
    async performSearch(keyword) {
        if (!keyword.trim()) return;

        try {
            const response = await fetch(`/api/video/search?keyword=${encodeURIComponent(keyword)}`);
            const result = await response.json();

            if (result.success) {
                this.displaySearchResults(result.videos, keyword);
            } else {
                this.showMessage('搜索失败: ' + result.message, 'error');
            }
        } catch (error) {
            this.showMessage('搜索失败: ' + error.message, 'error');
        }
    }

    // 显示搜索结果
    displaySearchResults(videos, keyword) {
        const videoGrid = document.querySelector('.video-grid');
        if (!videoGrid) return;

        videoGrid.innerHTML = '';

        if (videos.length === 0) {
            videoGrid.innerHTML = `
                <div class="no-results">
                    <h3>没有找到相关视频</h3>
                    <p>尝试使用其他关键词搜索</p>
                </div>
            `;
            return;
        }

        videos.forEach(video => {
            const videoCard = this.createVideoCard(video);
            videoGrid.appendChild(videoCard);
        });

        // 更新页面标题
        const pageTitle = document.querySelector('.page-title');
        if (pageTitle) {
            pageTitle.textContent = `搜索结果: "${keyword}" (${videos.length}个视频)`;
        }
    }

    // 创建视频卡片
    createVideoCard(video) {
        const card = document.createElement('div');
        card.className = 'video-card';
        card.innerHTML = `
            <div class="video-thumbnail">
                <div class="play-button">▶</div>
                🎬
            </div>
            <div class="video-info">
                <h3 class="video-title">${this.escapeHtml(video.title)}</h3>
                <p class="video-description">${this.escapeHtml(video.description || '')}</p>
                <div class="video-meta">
                    <span class="video-date">${this.formatDate(video.uploadTime)}</span>
                    <span class="video-size">${this.formatFileSize(video.fileSize)}</span>
                </div>
            </div>
        `;

        card.addEventListener('click', () => {
            window.location.href = `/video/${video.id}`;
        });

        return card;
    }

    // 设置视频卡片点击事件
    setupVideoCards() {
        document.addEventListener('click', (e) => {
            const videoCard = e.target.closest('.video-card');
            if (videoCard && videoCard.dataset.videoId) {
                window.location.href = `/video/${videoCard.dataset.videoId}`;
            }
        });
    }

    // 设置动画效果
    setupAnimations() {
        // 滚动显示动画
        const observerOptions = {
            threshold: 0.1,
            rootMargin: '0px 0px -50px 0px'
        };

        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.style.opacity = '1';
                    entry.target.style.transform = 'translateY(0)';
                }
            });
        }, observerOptions);

        // 观察所有需要动画的元素
        document.querySelectorAll('.video-card, .stat-card').forEach(el => {
            el.style.opacity = '0';
            el.style.transform = 'translateY(20px)';
            el.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
            observer.observe(el);
        });
    }

    // 显示消息
    showMessage(message, type = 'info') {
        const messageContainer = document.createElement('div');
        messageContainer.className = `message ${type}`;
        messageContainer.textContent = message;

        // 插入到页面顶部
        const mainContent = document.querySelector('.main-content');
        if (mainContent) {
            mainContent.insertBefore(messageContainer, mainContent.firstChild);
        } else {
            document.body.appendChild(messageContainer);
        }

        // 3秒后自动消失
        setTimeout(() => {
            messageContainer.remove();
        }, 3000);
    }

    // 工具函数
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN');
    }

    formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    new VideoPlatform();
});

// 视频播放器功能
class VideoPlayer {
    constructor(videoElement) {
        this.video = videoElement;
        this.init();
    }

    init() {
        if (!this.video) return;

        // 自定义控制栏
        this.setupCustomControls();
        
        // 键盘快捷键
        this.setupKeyboardControls();
        
        // 播放统计
        this.setupPlaybackTracking();
    }

    setupCustomControls() {
        // 这里可以添加自定义播放控制
        this.video.addEventListener('loadeddata', () => {
            console.log('视频加载完成');
        });

        this.video.addEventListener('play', () => {
            console.log('开始播放');
        });

        this.video.addEventListener('pause', () => {
            console.log('暂停播放');
        });
    }

    setupKeyboardControls() {
        document.addEventListener('keydown', (e) => {
            if (!this.video) return;

            switch (e.code) {
                case 'Space':
                    e.preventDefault();
                    if (this.video.paused) {
                        this.video.play();
                    } else {
                        this.video.pause();
                    }
                    break;
                case 'ArrowLeft':
                    e.preventDefault();
                    this.video.currentTime -= 10;
                    break;
                case 'ArrowRight':
                    e.preventDefault();
                    this.video.currentTime += 10;
                    break;
                case 'ArrowUp':
                    e.preventDefault();
                    this.video.volume = Math.min(1, this.video.volume + 0.1);
                    break;
                case 'ArrowDown':
                    e.preventDefault();
                    this.video.volume = Math.max(0, this.video.volume - 0.1);
                    break;
            }
        });
    }

    setupPlaybackTracking() {
        let hasStarted = false;
        
        this.video.addEventListener('play', () => {
            if (!hasStarted) {
                hasStarted = true;
                // 记录播放开始
                this.trackPlayback('start');
            }
        });

        this.video.addEventListener('ended', () => {
            // 记录播放完成
            this.trackPlayback('complete');
        });
    }

    trackPlayback(event) {
        // 这里可以发送播放统计到服务器
        console.log('播放事件:', event);
    }
}

// 如果页面有视频播放器，初始化它
document.addEventListener('DOMContentLoaded', () => {
    const videoElement = document.querySelector('.video-player video');
    if (videoElement) {
        new VideoPlayer(videoElement);
    }
});
